package com.guli.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;
import com.guli.common.utils.R;
import com.guli.product.dao.SpuInfoDao;
import com.guli.product.entity.*;
import com.guli.product.feign.SeckillFeign;
import com.guli.product.service.*;
import com.guli.product.vo.SeckillSkuVo;
import com.guli.product.vo.SkuItemSaleAttrVo;
import com.guli.product.vo.SkuItemVo;
import com.guli.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.product.dao.SkuInfoDao;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuInfoDao skuInfoDao;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SpuInfoDao spuInfoDao;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private SeckillFeign seckillFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String brandId = (String) params.get("brandId");
        String categoryId = (String) params.get("categoryId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        if (!StringUtils.isEmpty(categoryId) && !"0".equals(categoryId)) {
            wrapper.eq("category_id", categoryId);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper.like("sku_name", key);
        }
        if (!StringUtils.isEmpty(min) && !"0".equals(min)) {
            wrapper.ge("price", min);
        }
        if (!StringUtils.isEmpty(max) && !"0".equals(max)) {
            wrapper.le("price", max);
        }
        IPage<SkuInfoEntity> pages = skuInfoDao.selectPage(new Query<SkuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(pages);
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        //异步编排
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //sku基本信息获取 pms_sku_info
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVo.setInfo(skuInfo);
            return skuInfo;
        }, executor);

        CompletableFuture<Void> saleAttrValueFuture = infoFuture.thenAcceptAsync((res) -> {
            //获取spu的销售属性组合
            List<SkuItemSaleAttrVo> skuSaleAttrValue = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(skuSaleAttrValue);
        }, executor);

        CompletableFuture<Void> infoDescFuture = infoFuture.thenAcceptAsync(res -> {
            //获取spu的介绍
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService
                    .getOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", res.getSpuId()));
            skuItemVo.setDesc(spuInfoDesc);
        }, executor);

        CompletableFuture<Void> attrGroupFuture = infoFuture.thenAcceptAsync(res -> {
            //获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVoList = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCategoryId());
            skuItemVo.setGroupAttrs(attrGroupVoList);
        }, executor);

        //sku的图片信息 psm_sku_images
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntityList = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            skuItemVo.setImages(skuImagesEntityList);
        }, executor);

        //查询当前sku是否参与秒杀优惠
        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            R skuSeckillInfo = seckillFeign.getSkuSeckillInfo(skuId);
            if ((Integer) skuSeckillInfo.get("code") == 0) {
                Object data = skuSeckillInfo.get("data");
                SeckillSkuVo seckillSkuVo = JSON.parseObject(JSON.toJSONString(data), new TypeReference<SeckillSkuVo>() {
                });
                skuItemVo.setSeckillSkuVo(seckillSkuVo);
            }
        }, executor);

        try {
            CompletableFuture.allOf(infoFuture, saleAttrValueFuture, infoDescFuture, attrGroupFuture, imageFuture, secKillFuture).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(skuItemVo);
        return skuItemVo;
    }

    @Override
    public BigDecimal getWeight(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoDao
                .selectOne(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuId));
        Long spuId = skuInfo.getSpuId();
        SpuInfoEntity spuInfo = spuInfoDao.selectById(spuId);
        return spuInfo.getWeight();
    }

    @Override
    public List<SkuInfoEntity> skuInfos(List<Long> skuids) {
        List<SkuInfoEntity> skuInfoEntities = skuInfoDao.selectBatchIds(skuids);
        return skuInfoEntities;
    }

    @Override
    public Boolean handleUpdateSkuInfo(SkuInfoEntity skuInfo) {
        return this.updateById(skuInfo);
    }

    @Override
    public Boolean handleSaveSkuInfo(SkuInfoEntity skuInfo) {
        return this.save(skuInfo);
    }
}